﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Utils;

namespace Plugins.UserControls
{
	internal class PresetsDataSource<T>
	{
		#region Attributes

		public readonly string _filename;

		#endregion

		#region Public Methods

		public PresetsDataSource(string filename)
		{
			_filename = filename;
		}

		public void Save(IEnumerable<Preset<T>> presets)
		{
			BinaryFormatter formatter = new BinaryFormatter();

			using (FileStream stream = new FileStream(_filename, FileMode.OpenOrCreate))
			{
				formatter.Serialize(stream, presets.ToArray());
			}
		}

		public IEnumerable<Preset<T>> Load()
		{
			BinaryFormatter formatter = new BinaryFormatter();

			using (FileStream stream = new FileStream(_filename, FileMode.OpenOrCreate))
			{
				try
				{
					return (IEnumerable<Preset<T>>)formatter.Deserialize(stream);
				}
				catch (Exception ex)
				{
					ExceptionLogger.LogException("There was an error getting the presets from the file " + _filename + ". Returning an empty list", ex, false);
					return new List<Preset<T>>();
				}
			}
		}

		#endregion
	}
}
